package com.zhy.skinchangenow.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.*
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.DrawerListener
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.nineoldandroids.view.ViewHelper
import com.water.skin.SkinManager
import com.water.skin.callback.ISkinChangingCallback
import com.zhy.skinchangenow.R
import com.zhy.skinchangenow.test.TestTagActivity
import java.io.File
import java.util.*


class MainActivity : AppCompatActivity() {

    private var mDrawerLayout: DrawerLayout? = null
    private var mListView: ListView? = null
    private val mSkinPkgPath =
        Environment.getExternalStorageDirectory().toString() + File.separator + "skin_plugin.apk"

    private val mData: MutableList<String> = ArrayList(
        listOf(
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service",
            "Activity",
            "Service"
        )
    )

    private var mAdapter: ArrayAdapter<*>? = null

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        SkinManager.getInstance().register(this)

        setContentView(R.layout.activity_main)
        initView()
        initEvents()
        initXXPermissions()
    }

    private fun initXXPermissions() {
        XXPermissions.with(this)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        toast("获取录音和日历权限成功")
                    } else {
                        toast("获取部分权限成功，但部分权限未正常授予")
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        toast("被永久拒绝授权，请手动授予录音和日历权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    } else {
                        toast("获取录音和日历权限失败")
                    }
                }
            })
    }

    private fun toast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }

    private fun initEvents() {
        mListView = findViewById(R.id.id_listview)
        mListView!!.adapter = object : ArrayAdapter<String>(this, -1, mData) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view: View = convertView
                    ?: LayoutInflater.from(this@MainActivity).inflate(
                        R.layout.item, parent, false
                    )
                SkinManager.getInstance().injectSkin(view)
                val tv = view.findViewById<View>(R.id.id_tv_title) as TextView
                tv.text = getItem(position)
                return view
            }
        }.also { mAdapter = it }

        mDrawerLayout!!.setDrawerListener(object : DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {}
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                val mContent = mDrawerLayout!!.getChildAt(0)
                val scale = 1 - slideOffset
                val rightScale = 0.8f + scale * 0.2f
                if (drawerView.tag == "LEFT") {
                    val leftScale = 1 - 0.3f * scale
                    ViewHelper.setScaleX(drawerView, leftScale)
                    ViewHelper.setScaleY(drawerView, leftScale)
                    ViewHelper.setAlpha(drawerView, 0.6f + 0.4f * (1 - scale))
                    ViewHelper.setTranslationX(
                        mContent,
                        drawerView.measuredWidth * (1 - scale)
                    )
                    ViewHelper.setPivotX(mContent, 0f)
                    ViewHelper.setPivotY(
                        mContent, (
                                mContent.measuredHeight / 2).toFloat()
                    )
                    mContent.invalidate()
                    ViewHelper.setScaleX(mContent, rightScale)
                    ViewHelper.setScaleY(mContent, rightScale)
                }
            }

            override fun onDrawerOpened(drawerView: View) {}
            override fun onDrawerClosed(drawerView: View) {}
        })
    }

    private fun initView() {
        mDrawerLayout = findViewById(R.id.id_drawerLayout)

        val fm = supportFragmentManager
        val fragment = fm.findFragmentById(R.id.id_left_menu_container)
        if (fragment == null) {
            fm.beginTransaction().add(R.id.id_left_menu_container, MenuLeftFragment()).commit()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.id_action_plugin_skinchange -> {
                Log.i("MainActivity", "onOptionsItemSelected:$mSkinPkgPath")
                //----->/storage/emulated/0/skin_plugin.apk
                SkinManager.getInstance().changeSkin(
                    mSkinPkgPath,
                    "com.imooc.skin_plugin",
                    object : ISkinChangingCallback {

                        override fun onStart() {

                        }

                        override fun onError(e: Exception) {
                            Toast.makeText(
                                this@MainActivity,
                                "换肤失败:" + e.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                        override fun onComplete() {
                            Toast.makeText(this@MainActivity, "换肤成功", Toast.LENGTH_SHORT).show()
                        }
                    })
            }

            R.id.id_action_remove_any_skin -> SkinManager.getInstance().removeAnySkin()

            R.id.id_action_notify_lv -> {
                var i = 0
                val n = mData.size
                while (i < n) {
                    mData[i] = mData[i] + " changed"
                    i++
                }
                mAdapter!!.notifyDataSetChanged()
            }
            R.id.id_action_dynamic -> TestTagActivity.jumpTo(this)
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        SkinManager.getInstance().unregister(this)
    }

    companion object {
        fun jumpTo(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }
}